#coding:utf-8
import requests
from lxml import etree
import sys 
reload(sys) 
sys.setdefaultencoding( "utf-8" ) 

def login(session,headers):
    #登录页面
    url_login = 'https://accounts.douban.com/login'
    #post数据表单
    formdata = {
        'redir':'https://movie.douban.com/',#'https://www.douban.com',
        'form_email': 'jakejie@163.com',
        'form_password': '******',
        'login': u'登陆'
        }
    #尝试post数据
    r = session.post(url_login, data = formdata, headers = headers)
    html =r.content
    #print html
    tree = etree.HTML(html)
    #查找是否存在验证码图片
    captcha = tree.xpath("//form[@id='lzform']/div[6]/div[1]/img/@src")
    #存在验证码图片，则需要输入验证码，再进行下一步操作
    if captcha:
        captcha_url = captcha[0]
        #captcha_id
        captcha_id = tree.xpath("//form[@id='lzform']/div[6]/div[1]/div/input[2]/@value")
        print captcha_id[0]
        print captcha_url
        with open('image.png','wb') as f:
        	f.write(requests.get(captcha_url).content)
        f.close()
        print "打开当前路径下image.png文件，查看验证码图片！"
        print "输入验证码！！！"
        captcha_text = raw_input('Please input the captcha:')
        formdata['captcha-solution'] = captcha_text
        formdata['captcha-id'] = captcha_id[0]
        print formdata
        #再次post表单数据
        r = session.post(url_login, data = formdata, headers = headers)
        #print r.text
        print "登录成功！！！"
        return True

    else:
        print "不需要验证码！"
        print "登录成功！！！"
        return True

        #print r.text
#发布说说，分享生活点滴
def say(session):
    url = 'https://www.douban.com/'
    data = {
        'comment': '这是用Python程序提交上来的说说******',
        'ck': session.cookies.get('ck')
    }
    session.post(url,data=data)


def main():
    #浏览器请求头
    headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'}

    # 创建一个session用来处理
    session = requests.Session()
    TF = login(session,headers)
    #主页地址
    #my_url = 'https://www.douban.com/people/161586206/'
    #book_url = 'https://book.douban.com/'
    #book = session.get(book_url,headers = headers)
    #print book.text
    print session.cookies.get('ck')
    say(session)


if __name__ == '__main__':
    main()